package com.julis.thread;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.Constant;
import com.android.scj.tc.TcAppFolw;
import com.baseutils.SpfUtils;
import com.util.DelayTimeThread;
import com.util.HexUtil;

import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.concurrent.Future;

import com.julis.bean.FanHui;


/**
 * 脱机激活
 */
@SuppressWarnings("unused")
public class ActivateOfflineThread extends Thread {


	Handler handler;
	public static Bundle bundle;

	public static String OBUMAC_JC;

	public static long time;

	public static boolean isDetectSucess = false;
	public static boolean isSucess=false;

	DelayTimeThread delaytime = null;
	Future<?> f1 = null;
	Context context;
	TcAppFolw equiCon;
	String OBUMAC;

	public ActivateOfflineThread(Context context,String OBUMAC, Handler handler) {
		this.   handler=   handler;
		this.context=context;
		this.OBUMAC=OBUMAC;
		boolean	psamopen = (boolean) SpfUtils.get(context, Constant.Check_Psam, true);
 		      equiCon =  new TcAppFolw(context,psamopen);
	}

	public void print(String tag, String context) {
		Log.e(tag, context);
	}



	public void activateOBU(  ) throws NoSuchElementException, IOException,
			Exception {
		time = System.currentTimeMillis();

		equiCon.ObuOfflineActive();

		long lTmpTime = System.currentTimeMillis();
		time =  lTmpTime - time;
	}

	private void JhLoadBundMess()throws Exception
	{
		bundle = new Bundle();
		bundle.putString("OBUMAC", equiCon.GetOBUMAC());
		bundle.putString("OBUSERIALNUMBER",equiCon.GetOBUSerialNumber());
		bundle.putString("OBUSTATUS", equiCon.GetObuStatus());
		bundle.putString("OBUISSUER", HexUtil.HexToAsciiString(equiCon.GetOBUArea()));
		bundle.putString("OBUCONTRACTTYPE", equiCon.GetObuContractType());
		bundle.putString("OBUCONTRACT", equiCon.GetObuContract());
		bundle.putString("OBUBATTERY", equiCon.GetObuBattery());
		bundle.putString("OBUDATE", TcAppFolw.convertDate(equiCon.GetObuDate().substring(0, 8)));
		bundle.putString("OBUDATE2", TcAppFolw.convertDate(equiCon.GetObuDate().substring(8, 16)));
		bundle.putString("VLP",equiCon.VLP);

	}

	@Override
	public void run() {
		try {

			try {
				activateOBU( );
			} catch (Exception e) {
				throw new NumberFormatException(e.getMessage());
			}
			JhLoadBundMess();
			isSucess = true;
			Message message=new Message();

			FanHui fanHui=new FanHui();
			fanHui.setMessage("success脱机激活成功");
			fanHui.setBundle(bundle);
			message.what=3;
			message.obj=fanHui;
			handler.sendMessage(message);

		} catch (Exception e) {
			if (delaytime!=null)
				delaytime.isDelay(false);
 	    	isSucess = false;
			Log.e("test", "Error脱机激活失败：" + e.getMessage() );
			Message message=new Message();
			message.what=4;
			FanHui fanHui=new FanHui();
			fanHui.setMessage("Error脱机激活失败：" + e.getMessage());
			message.obj=fanHui;
			handler.sendMessage(message);

		}
	}
}
